<{include file="public/header.html"}>
<style>
.x-tree-node .x-tree-selected { background-color: #CCCCFF;}
.x-tree-selected-copy {background-color: blue;}
.x-tree-selected-cut  {background-color: red;}
</style>

<script language="javascript">
<!--
var TREE_TASK_PATH = "";
var COPY_NODE_ID = null;
var COPY_CUT_FLAG = "";
var B9_COM_MSG_PLS_SEL = "请选择";

Ext.QuickTips.init(false); 

if (Ext.form.ComboBox) {
    Ext.apply(Ext.form.ComboBox.prototype, {
        triggerAction:'all',
        selectOnFocus:true,
        editable:false,
        mode:'local',
        lazyInit:false,
        emptyText:B9_COM_MSG_PLS_SEL,
<{*  //valueField:'sValue', //此属性与TimeField冲突，不能统一设置，所以个别设置 *}>
        displayField:'sText',
        anchor:"95%"
        //width:"95%"
    });
}
if (Ext.form.TimeField) {
    Ext.apply(Ext.form.TimeField.prototype, {
        format:'H:i',
        hideLabel:true,
        emptyText:'',
        increment:10,
        maxLength:5,
        anchor:"",
        width:70
   });
}

var addTaskMenu = new Ext.menu.Menu({
    id: 'add_Task_Menu',
    items: [
        {id:"addTaskAfter" ,handler:function(){doAddTask("after");},
            text:"添加在此任务之后"},
        {id:"addTaskBefore",handler:function(){doAddTask("before");},
            text:"添加在此任务之前"},
        {id:"addTaskInside",handler:function(){doAddTask("inside");},
            text:"添加为子任务"},
        {id:"addTaskLast"  ,handler:function(){doAddTask("last");},
            text:"添加到最后"}]
});

var treeRightMenu = new Ext.menu.Menu({
    id: 'treeMenu',
    items:[
      {id:"trmAdd",icon: '../../images/btn/add.gif', text: '添加新任务', menu:addTaskMenu},
      {id:"trmDel",icon: '../../images/btn/delete.gif', text: '删除当前任务',disabled:true,handler:doDelTask},'-',
      {id:'trmCopy',icon: '../../images/btn/copy.gif', text: '复制任务',handler:doCopy},
      {id:'trmCut',icon: '../../images/btn/cut.gif', text: '剪切任务',handler:doCut},
      {id:'trmPaste',icon: '../../images/btn/paste.gif', text: '粘帖任务',disabled:true,handler:doPaste},'-',
      {id:'trmUp',text:'向上移动',icon: '../../images/btn/up.gif',handler:doUp},
      {id:'trmDown',icon: '../../images/btn/down.gif', text: '向下移动',handler:doDown},
      {id:'trmUpGrade',icon: '../../images/btn/upGrade.gif',text: '升级',handler:doUpGrade},
      {id:'trmDownGrade',icon: '../../images/btn/downGrade.gif',text: '降级',handler:doDownGrade}
      
    ]
});

var taskTree = new Ext.tree.TreePanel({
    title       : 'Task Tree',
    region      : 'west',
    split       : true,
    width       : 240,
    collapsible : true,
    margins     : '3 0 3 3',
    cmargins    : '1 1 1 1',
    tools       : [{id:'refresh',qtip:'刷新任务树',handler:function() {doReloadTree(true);} }],
    tbar        : [{id:"barUp",icon: '../../images/btn/up.gif', cls: 'x-btn-icon',tooltip: '向上移动',handler:doUp},
                  {id:"barDown",icon: '../../images/btn/down.gif', cls: 'x-btn-icon',tooltip: '向下移动',handler:doDown},
                  {id:"barUpGrade",icon: '../../images/btn/upGrade.gif', cls: 'x-btn-icon',tooltip: '升级',handler:doUpGrade},
                  {id:"barDownGrade",icon: '../../images/btn/downGrade.gif', cls: 'x-btn-icon',tooltip: '降级',handler:doDownGrade},'-',
                  {id:"barCopy",icon: '../../images/btn/copy.gif', cls: 'x-btn-icon',tooltip: '复制任务',handler:doCopy},
                  {id:"barCut",icon: '../../images/btn/cut.gif', cls: 'x-btn-icon',tooltip: '剪切任务',handler:doCut},
                  {id:"barPaste",icon: '../../images/btn/paste.gif', cls: 'x-btn-icon',tooltip: '粘帖任务',disabled:true,handler:doPaste},'-',
                  {id:"barAdd",icon: '../../images/btn/add.gif', cls: 'x-btn-icon',tooltip: '添加新任务',menu:addTaskMenu},
                  {id:"barDel",icon: '../../images/btn/delete.gif', cls: 'x-btn-icon',tooltip: '删除当前任务',disabled:true,handler:doDelTask}
                ],

    autoScroll:true,
    animate:true,
    enableDD:false,
    containerScroll: true,
    rootVisible: false,
    stateful:false,

    //create TreeLoader
    loader:new Ext.tree.TreeLoader({ dataUrl:'taskAjax.php?strAction=treelist' }),
    root: new Ext.tree.AsyncTreeNode({text:'Task Tree',draggable:false,id:'0'}) 
});
taskTree.on('contextmenu',function(node,e) {
    //node.select();
    //checkNodeStatus(node);
    node.fireEvent("click",node);
    treeRightMenu.showAt(e.getXY());
});
<{*
taskTree.on("load",function(node) {
    if (COPY_CUT_FLAG=="copy" && COPY_NODE_ID!=null) {
        var curNode = taskTree.getNodeById(COPY_NODE_ID);
        resetClass(curNode);
        curNode.select();
        curNode.getUI().addClass("x-tree-selected-copy");
        //COPY_CUT_FLAG = "copy";
    }
});
*}>

function getSelectedNode() {
    var curNode = taskTree.getSelectionModel().getSelectedNode();
    if (curNode==null || curNode.id==null || curNode.id=="") {
        Ext.Msg.alert('操作失败', '请在任务树上选择一个任务');
        return false;
    } else {
        return curNode;
    }
}
function fn_sDd(cmp,flag) {
    var box = Ext.getCmp(cmp);
    if (box != null) box.setDisabled(flag);
}
function checkNodeStatus(curNode) {
    var flag1=false,flag2=false,flag3=false;
    var prevNode = curNode.previousSibling;
    var nextNode = curNode.nextSibling;
    if (curNode.isLeaf()) {
        flag1 = (prevNode!=null && prevNode.isLeaf());
        flag2 = (nextNode!=null && nextNode.isLeaf());
        flag3 = true; //enable to cut or delete
    }
    var flag4=(COPY_NODE_ID==null);
    var flag5=(curNode.attributes.pid=="0");
    var flag6=(prevNode==null);

    fn_sDd("trmUp",!flag1);
    fn_sDd("barUp",!flag1);
    fn_sDd("trmDown",!flag2);
    fn_sDd("barDown",!flag2);
    fn_sDd("trmPaste",flag4);
    fn_sDd("barPaste",flag4);
    fn_sDd("trmCut",!flag3);
    fn_sDd("barCut",!flag3);
    fn_sDd("trmDel",!flag3);
    fn_sDd("barDel",!flag3);
    fn_sDd("btnDel",!flag3);
    fn_sDd("trmUpGrade",flag5);
    fn_sDd("barUpGrade",flag5);
    fn_sDd("trmDownGrade",flag6);
    fn_sDd("barDownGrade",flag6);
}
function doUp() {
    var curNode = getSelectedNode();
    if (curNode) {
        var prevNode = curNode.previousSibling;
        var sOrderNumb = curNode.text.substr(0,curNode.text.indexOf(":"));
        Ext.Ajax.request({
            url: 'taskAjax.php',
            params: {strTaskID:curNode.id,strPrevTaskID:prevNode.id,strAction:"moveup",strOrderNumb:sOrderNumb }
        });
        doReloadTree(true);
    }
}
function doDown() {
    var curNode = getSelectedNode();
    if (curNode) {
        var nextNode = curNode.nextSibling;
        var sOrderNumb = curNode.text.substr(0,curNode.text.indexOf(":"));
        Ext.Ajax.request({
            url: 'taskAjax.php',
            params: {strTaskID:curNode.id,strNextTaskID:nextNode.id,strAction:"movedn",strOrderNumb:sOrderNumb }
        });
        doReloadTree(true);
    }
}
function doUpGrade() {
    var curNode = getSelectedNode();
    if (curNode) {
        var nextNode = curNode.nextSibling;
        var sOrderNumb = "0";
        if (nextNode!=null && nextNode.text!="") {
            sOrderNumb = nextNode.text.substr(0,nextNode.text.indexOf(":"));
        }
        var parentid = curNode.parentNode.attributes.pid;
        if (parentid==null || parentid=="") parentid="0";
        Ext.Ajax.request({
            url: 'taskAjax.php',
            success: function() {doReloadTree(true);},
            params: {strTaskID:curNode.id,strNewParentID:parentid,strAction:"upgrade",strParentID:curNode.parentNode.id,strOrderNumb:sOrderNumb }
        });
    }
}
function doDownGrade() {
    var curNode = getSelectedNode();
    if (curNode) {
        var prevNode = curNode.previousSibling;
        Ext.Ajax.request({
            url: 'taskAjax.php',
            success: function() {doReloadTree(true);},
            params: {strTaskID:curNode.id,strNewParentID:prevNode.id,strAction:"downgrade" }
        });
    }
}
function resetClass(treeNode) {
    if (treeNode != null) {
        treeNode.getUI().removeClass(["x-tree-selected","x-tree-selected-copy","x-tree-selected-cut"]);
    }
}
function doCopy() {
    var curNode = getSelectedNode();
    if (curNode) {
        if (COPY_NODE_ID != null) {
            resetClass(COPY_NODE_ID);
        }
        resetClass(curNode);
        curNode.getUI().addClass("x-tree-selected-copy");
        COPY_NODE_ID = curNode;
        COPY_CUT_FLAG = "copy";
        fn_sDd("trmPaste",false);
        fn_sDd("barPaste",false);
    }
}
function doCut() {
    var curNode = getSelectedNode();
    if (curNode) {
        if (COPY_NODE_ID != null) {
            resetClass(COPY_NODE_ID);
        }
        resetClass(curNode);
        curNode.getUI().addClass("x-tree-selected-cut");
        COPY_NODE_ID = curNode;
        COPY_CUT_FLAG = "cut";
        fn_sDd("trmPaste",false);
        fn_sDd("barPaste",false);
    }
}
function doPaste() {
    var curNode = getSelectedNode();
    if (COPY_NODE_ID==null || COPY_NODE_ID.id==curNode.id && COPY_CUT_FLAG=='cut') {return false;}

    Ext.Ajax.request({
        url: 'taskAjax.php',
        params: {strTaskID:COPY_NODE_ID.id,strNewTaskID:curNode.id,strAction:COPY_CUT_FLAG,strIsFolder:(curNode.isLeaf()?'0':'1') }
    });
    if (COPY_CUT_FLAG=="cut") {
        COPY_NODE_ID = null;
    }
    doReloadTree(true);
}
function calcDuration() {
    var sStartDate = getFDate("sPlanStartDate")+" "+Ext.getCmp("sPlanStartTime").getValue()+":00";
    var sFinishDate = getFDate("sPlanFinishDate")+" "+Ext.getCmp("sPlanFinishTime").getValue()+":00";
    var isAutoCalc = Ext.getCmp("isAutoCalc").checked;

    if (sStartDate!="" && sFinishDate!="") {
        if (sStartDate > sFinishDate) {
            Ext.Msg.alert("错误", "计划开始时间不能比计划完成时间晚");
            Ext.getCmp("sDuration").setValue("");
            return false;
        } else if (isAutoCalc) {
            Ext.Ajax.request({
                url:'calcDuration.php',
                params:{strStartDate:sStartDate,strFinishDate:sFinishDate},
                success:function(resp,opts) {
                    ///Ext.Msg.alert('提示', "duration:"+resp.responseText);
                    //element does not exist setValue function
                    Ext.getCmp("sDuration").setValue(resp.responseText);
                }
            });
        }
    };
    //Ext.Msg.alert('information', 'start date:'+sStartDate+",finishdate:"+sFinishDate);
    return true;
}
function getFDate(dateId) {
    var sDate = Ext.getCmp(dateId).getValue();
    if (sDate != null && sDate != "") {
        return sDate.format('Y-m-d');
    } else {
        return "";
    }
}

var taskForm = new Ext.FormPanel({
    labelAlign: 'right',
    frame :true,
    layout: 'form',
    title : '任务基本信息',
    reader: Ext.data.JsonReader({
        successProperty:"success",
        totalProperty:"total", 
        id: "strTaskID" 
        }, ['strTaskID','strOrderNumb','strPriority','strWbsCode','strTaskName','strTaskType',
            'strPlanStartDate','strPlanStartTime','strPlanFinishDate','strPlanFinishTime',
            'strLimitType','strLimitDate','strLimitTime','strTaskInfo','strFinishPercent',
            'strFactStartDate','strFactStartTime','strFactFinishDate','strFactFinishTime','strFinishInfo',
            'strDuration','strCreateUser','strCreateDate','strUpdateDate'] 
        ),

    items: [{
        xtype:"panel",
        layout:"column",
        anchor:'100%',
        items:[{
            columnWidth:.3,
            layout:'form',
            items :[{xtype:"numberfield", fieldLabel:"任务号", name:"strOrderNumb",id:"idOrderNumb",
                     readOnly:true,maxLength:10,width:80},
                    {xtype:"hidden",name:"strTaskID",id:'sTaskID',value:''},
                    {xtype:"hidden",name:"strTaskWhere",id:'sTaskWhere',value:''},
                    {xtype:"hidden",name:"strOldOrderNumb",id:'sOldOrderNumb',value:''},
                    {xtype:"hidden",name:"strIsLeaf",id:'sIsLeaf',value:''}]
        },{
            columnWidth:.3,
            layout:'form',
            items:[{xtype:"combo",hiddenName:"strPriority",fieldLabel:"优先级",forceSelection:true,
                value:'<{ $aTask.PRIORITY }>',valueField:'sValue',
                store:new Ext.data.SimpleStore({
                    data:<{ $sImportance }>,
                    fields:['sValue','sText']
                })
            }]
        },{
            columnWidth:.4,
            layout:'form',
            items :[{xtype:"textfield", fieldLabel:"WBS编号", name:"strWbsCode", 
                     maxLength:40,anchor:'96%'}]
        }]
    },{
        xtype:'textfield',fieldLabel:'任务名称',name:'strTaskName',anchor:'96%',vtype:'dblCharField',
        maxLength:200,allowBlank:false
    },{
        xtype:"panel",
        layout:"column",
        anchor:'100%',
        items:[{
            columnWidth:.3,
            layout:'form',
            items :[{xtype:"datefield",fieldLabel: '计划开始时间',name:'strPlanStartDate',id:'sPlanStartDate',allowBlank:false,
                value:'<{ $aTask.PLANSTARTDATE }>',listeners:{'change':calcDuration}}]
        },{
            columnWidth:.2,
            layout:'form',
            items :[{xtype:"timefield",name:'strPlanStartTime',id:'sPlanStartTime',
                value:'<{ $aProject.AMSTARTTIME }>',listeners:{'change':calcDuration}}]
        },{
            columnWidth:.3,
            layout:'form',
            items : [{xtype:"datefield",fieldLabel:'计划完成时间',name:'strPlanFinishDate',id:'sPlanFinishDate',allowBlank:false,
                value:'<{ $aTask.PLANFINISHDATE }>',listeners:{'change':calcDuration}}]
        },{
            columnWidth:.2,
            layout:'form',
            items :[{xtype:"timefield",name:'strPlanFinishTime',id:'sPlanFinishTime',value:'<{ $aProject.PMENDTIME }>',
                listeners:{'change':calcDuration}}]
        }]
    },{
        xtype:"panel",
        layout:"column",
        anchor:'100%',
        items:[{
            columnWidth:.3,
            layout:'form',
            items :[{xtype:"textfield", fieldLabel:"工期(工作日)", name:"strDuration",id:"sDuration",
                     maxLength:10,width:100}]
        },{
            columnWidth:.2,
            layout:'form',
            items : [{xtype:'checkbox',hideLabel:true,boxLabel:'估计工期',checked:false,id:"isEstimate"}]
        },{
            columnWidth:.2,
            layout:'form',
            items : [{xtype:'checkbox',hideLabel:true,boxLabel:'自动计算工期',checked:true,
                id:"isAutoCalc"}]
        },{
            columnWidth:.3,
            layout:'form',
            items:[{xtype:"combo",hiddenName:"strTaskType",fieldLabel:"任务类型",valueField:'sValue',
                value:'<{ $aTask.TASKTYPE }>',
                store:new Ext.data.SimpleStore({
                    data  :<{ $sTaskType }>,
                    fields:['sValue','sText']
                }) }]
        }]
    },{
        xtype:"panel",
        layout:"column",
        anchor:'100%',
        items:[{
            columnWidth:.5,
            layout:'form',
            items:[{xtype:"combo",hiddenName:"strLimitType",id:'sLimitType',fieldLabel:"限制类型",forceSelection:true,
                valueField:'sValue',value:'<{ $aTask.LIMITTYPE }>',
                store:new Ext.data.SimpleStore({
                    data  :<{ $sTaskLimitType }>,
                    fields:['sValue','sText']
                }) }]
        },{
            columnWidth:.3,
            layout:'form',
            items : [{xtype:"datefield",fieldLabel:'限制日期',name:'strLimitDate',id:'sLimitDate'}]
        },{
            columnWidth:.2,
            layout:'form',
            items :[{xtype:"timefield",name:'strLimitTime'}]
        }]
    },{
        xtype:'htmleditor', name:'strTaskInfo',
        fieldLabel:'任务详细说明',
        height:80, width:'98%'
    },{
        xtype:"panel",
        layout:"column",
        anchor:'100%',
        items:[{
            columnWidth:.5,
            layout:'form',
            items : [{xtype:"combo",hiddenName:"strFinishPercent",fieldLabel:"完成百分比",
                valueField:'sValue',value:'0',
                store:new Ext.data.SimpleStore({
                    data: [ <{ section name="loop_finish" loop=100 step=5 }>
                            ["<{ $smarty.section.loop_finish.index }>","<{ $smarty.section.loop_finish.index }>%"],
                            <{ /section }> ['100','100%']],
                    fields:['sValue','sText']
                }) }]
        },{
            columnWidth:.5,
            layout:'form',
            items : [{xtype:'checkbox',fieldLabel:"里程碑",boxLabel:'标记为里程碑',
                        id:"isMilestone"}]
        }]
    },{
        xtype:"panel",
        layout:"column",
        anchor:'100%',
        items:[{
            columnWidth:.3,
            layout:'form',
            items :[{xtype:"datefield",fieldLabel: '实际开始时间',name:'strFactStartDate',id:'sFactStartDate'}]
        },{
            columnWidth:.2,
            layout:'form',
            items :[{xtype:"timefield",name:'strFactStartTime',id:'sFactStartTime',value:'<{ $aProject.AMSTARTTIME }>'}]
        },{
            columnWidth:.3,
            layout:'form',
            items : [{xtype:"datefield",fieldLabel:'实际完成时间',name:'strFactFinishDate',id:'sFactFinishDate'}]
        },{
            columnWidth:.2,
            layout:'form',
            items :[{xtype:"timefield",name:'strFactFinishTime',id:'sFactFinishTime',value:'<{ $aProject.PMENDTIME }>'}]
        }]
    },{
        xtype:'htmleditor', name:'strFinishInfo',
        fieldLabel:'完成情况说明',value:'',
        height:80,width:'98%'
        
    },{
        xtype:"panel",
        layout:"column",
        anchor:'100%',
        items:[{
            columnWidth:.36,
            layout:'form',
            items :[{xtype:"textfield", fieldLabel:"创建者", name:"strCreateUser",readOnly:true,
                anchor:'98%'}]
        },{
            columnWidth:.32,
            layout:'form',
            items :[{xtype:"textfield", fieldLabel:"创建时间", name:"strCreateDate",readOnly:true,
                anchor:'98%'}]
        },{
            columnWidth:.32,
            layout:'form',
            items :[{xtype:"textfield", fieldLabel:"最后更改时间", name:"strUpdateDate",
                anchor:'98%',readOnly:true}]
        }]
    }],

    buttons: [{
            text:"删 除",id:'btnDel',handler:doDelTask,disabled:true
        },{
            text: '保 存',id:'btnSave',handler:doSaveTask //handler:function() {taskForm.form.submit();} 
        },{
            text: '取 消',id:'btnCanel',handler:function() { doReloadTree(false);}
        }]
});

taskTree.on("click",function(node) {
    if (node!=null && node.id==Ext.getCmp("sTaskID").getValue() && Ext.getCmp("idOrderNumb").getValue()!="") {
        return true; //has exist
    }
    taskForm.getForm().load({
        url:'./taskAjax.php', 
        //waitMsg:'正在载入数据...', 
        params:{ strTaskID:node.id,strAction:ACTION_VIEW},

        success : function(form, action){
            Ext.getCmp("isEstimate").setValue(action.result.data.strIsEstimate);
            Ext.getCmp("isMilestone").setValue(action.result.data.strIsMilestone);
            taskForm.setTitle('任务基本信息');

            loadPretask(node.id);
            loadRes(node.id);

            if (Ext.getCmp("sTaskID").getValue() != "") {
                fn_sDd("btnAdd1",false);
                fn_sDd("btnAdd2",false);
                fn_sDd("btnDel1",false);
                fn_sDd("btnDel2",false);
                fn_sDd("btnDel",false);
                fn_sDd("trmDel",false);
                fn_sDd("barDel",false);
            }
            node.select();
            checkNodeStatus(node);
            //alert("sTaskID:"+Ext.getCmp("sTaskID").getValue());
        },
        failure : function(form, action){
            Ext.Msg.alert('错误', '数据加载失败！错误信息：'+action.response.responseText);
        }
    });
    TREE_TASK_PATH = node.getPath();
    //alert("Path:"+TREE_TASK_PATH);
});

function checkTaskForm() {
    if (!calcDuration()) return false;

    var sStartDate = getFDate("sFactStartDate");
    var sFinishDate = getFDate("sFactFinishDate");
    if (sStartDate!="" && sFinishDate!="") {
        sStartDate = sStartDate+" "+Ext.getCmp("sFactStartTime").getValue()+":00";
        sFinishDate = sFinishDate+" "+Ext.getCmp("sFactFinishTime").getValue()+":00";
        if (sStartDate >= sFinishDate) {
            Ext.Msg.alert("错误", "实际开始时间不能比实际完成时间晚");
            return false;
        }
    }

    var sLimitType = Ext.getCmp("sLimitType").getValue();
    var sLimitDate = Ext.getCmp("sLimitDate").getValue();
    if (sLimitType=="7" || sLimitType=="8") {
        if (sLimitDate!="") {
            Ext.Msg.alert("错误", "这种限制类型不能设定限制日期");
            return false;
        }
    } else if (sLimitDate=="") {
        Ext.Msg.alert("错误", "这种限制类型必须设定限制日期");
        return false;
    }
    return true;
}
function doReloadTree(isTree) {
    if (isTree) {
        taskTree.getRootNode().reload();
    }
    taskForm.form.reset();
    fn_sDd("btnDel",true);
    fn_sDd("trmDel",true);
    fn_sDd("barDel",true);
}
function doAddTask(sTaskWhere) {
    taskForm.form.reset();

    var sOrderNumb="",sNodeText="",sTaskID="";
    var curNode = taskTree.getSelectionModel().getSelectedNode();
    if (curNode != null) {
        sTaskID   = curNode.id;
        sNodeText = curNode.text;
        sOrderNumb = sNodeText.substr(0,sNodeText.indexOf(":"));
    } else {
        sTaskWhere = "last";
    }
    var sTitle = '任务基本信息 -- ';
    if (sTaskWhere=="after") {
        sTitle += "新任务添加在("+sNodeText+")之后";
    } else if (sTaskWhere=="before") {
        sTitle += "新任务添加在("+sNodeText+")之前";
    } else if (sTaskWhere=="inside") {
        sTitle += "新任务添加为("+sNodeText+")的子任务";
    } else {
        sTitle += "新任务添加在最后";
    }
    taskForm.setTitle(sTitle);

    Ext.getCmp("sOldOrderNumb").setValue(sOrderNumb);
    Ext.getCmp("sTaskWhere").setValue(sTaskWhere);
    Ext.getCmp("sTaskID").setValue(sTaskID);
    Ext.getCmp("sIsLeaf").setValue(curNode==null||curNode.leaf?'doc':'folder');

    fn_sDd("btnAdd1",true);
    fn_sDd("btnAdd2",true);
    fn_sDd("btnDel1",true);
    fn_sDd("btnDel2",true);
    fn_sDd("btnDel",true);
    fn_sDd("trmDel",true);
    fn_sDd("barDel",true);
}
function doSaveTask() {
    var ff = taskForm.getForm();
    var curNode = null;
    if (ff.isValid()) {
        if (!checkTaskForm()) return false;
        var sAction = (Ext.getCmp("idOrderNumb").getValue()=="" ? ACTION_INSERT : ACTION_UPDATE);
        ff.submit({
            url     : './taskAjax.php',
            method  : 'POST',
            //waitMsg : '正在保存数据...',
            params  : {strAction:sAction,strIsEstimate:(Ext.getCmp("isEstimate").checked?"1":"0"),
                       strIsMilestone:(Ext.getCmp("isMilestone").checked?"1":"0")},
            success : function(form, action){
                //Ext.Msg.alert('info', action.response.responseText);
                Ext.Msg.alert('提示', action.result.msg);
                if (sAction == ACTION_INSERT) {
                    Ext.getCmp("sTaskID").setValue(action.result.taskID);
                    Ext.getCmp("idOrderNumb").setValue(action.result.orderNumb);
                    curNode = taskTree.getNodeById(action.result.taskID);
                    if (curNode != null) TREE_TASK_PATH = curNode.getPath();
                }
                taskTree.getRootNode().reload();
                taskTree.selectPath(TREE_TASK_PATH);
            },
            failure : function(form, action) {
                ///Ext.Msg.alert('错误', action.response.responseText);
                Ext.Msg.alert('错误', '数据保存失败！');
            }
        });
    } else { //form checked is invalid
        Ext.Msg.alert('错误',"填写的数据有错误，请检查");
    }
};
function doDelTask() {
    var sTaskID = Ext.getCmp("sTaskID").getValue();
    if (sTaskID == "") {
        Ext.Msg.alert('提示', '请先选择具体的任务，再进行删除');
    }
    if (taskTree.getNodeById(sTaskID).isLeaf()) {
        Ext.Msg.confirm('Confirm', '您确定要删除此任务吗?', function (btn) {
            if (btn == "yes") {
                taskForm.getForm().submit({
                    url     : './taskAjax.php',
                    method  : 'POST',
                    //waitMsg : '正在删除数据...',
                    params  : {strAction:ACTION_DELETE},
                    success : function(form,action) {
                        //Ext.Msg.alert('提示', "该任务已经删除成功");
                        taskTree.getRootNode().reload();
                    },
                    failure : function(form,action) {
                        Ext.Msg.alert('错误', '数据删除失败！');
                    }
                });
            }
        });
    } else {
        Ext.Msg.alert('提示', '请先删除其子任务，再删除此任务大纲');
    }
}

var xgPreTask = new Ext.Panel({
    frame :true,
    region:'center',
    layout:'form',
    title :'该任务的前置任务信息',
    tbar:[{
        id:'btnAdd1',
        disabled:true,
        text:'新增',
        tooltip:'新增前置任务',
        iconCls:'btn_add',
        handler:function() {
            winPreTask.show();
            frmPreTask.form.reset();
            Ext.getCmp("idPreTaskID").store.load({params:{strOrderNumb:Ext.getCmp("idOrderNumb").getValue()}});
            Ext.getCmp("idPreTaskType").setValue("FS");
            fn_sDd("btnPreTaskDel",true);}
    }, '-', {
        id:"btnDel1",
        disabled:true,
        text:'批量删除',
        tooltip:'批量删除已经选择的前置任务',
        iconCls:'btn_remove',
        handler:function() {
            var records = $("input[name='cbPretaskID']:checked"); //得到被选择的行的数组
            var preIDs = "";
            records.each(function() {
                if (preIDs.length > 0) {
                    preIDs += "," + this.value;
                } else {
                    preIDs += this.value;
                }
            });
            
            if (preIDs.length == 0){ 
                Ext.Msg.alert("系统提示信息","请先选择一行或多行进行删除！");
            } else {
                Ext.Ajax.request({
                    url : './taskAjax.php',
                    params : {strAction:'batchDelPreTask',strPreIDs:preIDs },
                    success: function() {loadPretask("");},
                    failure: function(form,action) {
                        Ext.Msg.alert('批量删除数据',action.result.msg);
                    }
                });
            }
        }
    }, '-', {
        text:'刷新',
        tooltip:'重新加载数据',
        iconCls:'btn_refresh',
        handler:function() {loadPretask("");}
    }]
});

function selAllPretask(box) {
    var chk = $("input[name='cbPretaskID']");
    if (chk != null) {
        chk.attr("checked",box.checked);
    }
}
function loadPretask(taskId) {
    if (taskId=="" || taskId<0) {
        taskId = Ext.getCmp("sTaskID").getValue();
    }
    var tblHeader = '<table width="100%" bgColor="#FFFFFF" border="1" class="table1">'+
	    '<thead><tr>'+
	    '<th title="选择删除"><input type="checkbox" name="chkPretaskID" onclick="selAllPretask(this);"/>全选择/全不选</th>'+
	    '<th title="前置任务名称">前置任务名称</th>'+
	    '<th title="类型">类型</th>'+
	    '<th title="延隔时间">延隔时间</th>'+
	    '<th title="备注">备注</th>'+
	    '</tr></thead>';

    Ext.Ajax.request({
        url : './taskAjax.php',
        params : {strAction:'preTaskList',strTaskID:taskId },
        success: function(response,options ) {
            //Ext.Msg.alert('info', response.responseText);
            var rtnData = Ext.decode(response.responseText);
            var tblBody = "";
            if (rtnData.total > 0) {
                for (var i=0; i<rtnData.data.length; i++) {
                    tblBody += '<tr '+(i % 2 === 0 ? "" : "class=t1")+'>'+
                    '<td><input type="checkbox" name="cbPretaskID" value="'+rtnData.data[i].strID+'"/>'+
                    '<a href="javascript:editPretask('+rtnData.data[i].strID+');"> 修改</a></td>'+
                    '<td>'+rtnData.data[i].strTaskName+'</td>'+
                    '<td align="center">'+rtnData.data[i].strPreTaskType+'</td>'+
                    '<td>'+rtnData.data[i].strStayTime+'</td>'+
                    '<td>'+rtnData.data[i].strRemark+'</td>'+
                    '</tr>';
                }
            }
            if (xgPreTask && xgPreTask.body) {
                xgPreTask.body.update(tblHeader+tblBody+'</table>');
            }
        },
        failure: function(response,options ) {
            Ext.Msg.alert('error',response.responseText);
        }
    });
}
function editPretask(sId) {
    Ext.Ajax.request({
        url : './taskAjax.php',
        params : {strAction:'preTaskList',strID:sId },
        success: function(response,options ) {
            //Ext.Msg.alert('info', response.responseText);
            var rtnData = Ext.decode(response.responseText);
            if (rtnData.total >= 1) {
                var rd=rtnData.data[0];
                winPreTask.show();
                frmPreTask.form.reset();
                Ext.getCmp("idPreTaskID").store.load({params:{strOrderNumb:Ext.getCmp("idOrderNumb").getValue()}});
                fn_sDd("btnPreTaskDel",false);
                Ext.getCmp("idPreID").setValue(rd.strID);
                Ext.getCmp("idStayTime").setValue(rd.strStayTime);
                Ext.getCmp("idPreRemark").setValue(rd.strRemark);
                Ext.getCmp("idPreTaskID").setValue(rd.strTaskName);
                Ext.getCmp("idPreTaskID").selectByValue(rd.strPreTaskID,true);
                Ext.getCmp("idPreTaskType").setValue(rd.strPreType);
                Ext.getCmp("idPreTaskType").selectByValue(rd.strPreType,true);
            }
        },
        failure: function(response,options ) {
            Ext.Msg.alert('error',response.responseText);
        }
    });
}

//维护前置任务信息
var frmPreTask = new Ext.FormPanel({
    baseCls: 'x-plain',
    labelWidth: 80,
    labelAlign: 'left',
    buttonAlign:'center',
    bodyStyle : 'padding-top:5px',
    defaultWidth:'180',
    items: [{
        xtype:"combo",id:"idPreTaskID",fieldLabel:"前置任务",displayField:'sText',valueField:'sValue',
        allowBlank:false, blankText:'前置任务不能为空',mode:'remote',anchor:'94%',hiddenName:"strPreTaskID",
        store:new Ext.data.JsonStore({url:'taskAjax.php?strAction=preTaskNameList',root:'data',
            listeners:{beforeload:function(store,option) {
                    option.params = {strOrderNumb:Ext.getCmp("idOrderNumb").getValue()};
                    }},
            fields:['sValue','sText'] })
    },{
        xtype:"combo",id:"idPreTaskType",fieldLabel:"前置任务类型",displayField:'sText',valueField:'sValue',
        allowBlank:false, blankText:'前置任务类型不能为空',anchor:'94%',hiddenName:"strPreTaskType",
        store:new Ext.data.SimpleStore({
            data: <{ $sPreTaskType }>,
            fields:['sValue','sText']
        })
    },{xtype:"numberfield",fieldLabel:"延隔时间",name:"strStayTime",id:"idStayTime",maxLength:6,width:80
    },{xtype:"textfield",fieldLabel:'备注',id:'idPreRemark',name:"strPreRemark",vtype:'dblCharField',anchor:'94%',maxLength:120},
    {xtype:"hidden",name:"strPreID",id:'idPreID',value:''}],

    buttons: [{
        text:'保存',
        handler:function(){
            if  (frmPreTask.form.isValid()) {
                frmPreTask.form.submit({
                    url : (Ext.getCmp("idPreID").getValue()==""?"./checkPreTask.php":"./taskAjax.php"),
                    //url : "./taskAjax.php",
                    method: 'POST',
                    params:{strAction:(Ext.getCmp("idPreID").getValue()==""?'addPreTask':'updatePreTask'),
                            strTaskID:Ext.getCmp("sTaskID").getValue()},
                    success:function(form, action){loadPretask(""); winPreTask.hide();},
                    failure:function(form, action){Ext.Msg.alert('数据保存失败！',action.result.msg);}
                });
            } else {
                Ext.Msg.show({title:'错误', msg:"数据错误，请检查", buttons: Ext.Msg.OK, icon: Ext.Msg.ERROR});
            }
        }
    },{
        text:'删除',id:'btnPreTaskDel',
        handler:function(){
            frmPreTask.form.submit({
                url     : './taskAjax.php',
                method  : 'POST',
                params  : {strAction:'deletePreTask'},
                success : function(form,action) {loadPretask(""); winPreTask.hide();},
                failure : function(form,action) {Ext.Msg.alert('数据删除失败！',action.result.msg);}
            });
        }
    },{
        text:'取消',handler:function(){winPreTask.hide();}
     }]
});
var winPreTask = new Ext.Window({
    title: '前置任务维护',
    width: 360,height:190,collapsible:true, maximizable:false,
    layout:'fit',plain:true,bodyStyle:'padding:5px;',
    modal:true,closeAction:'hide',items:frmPreTask
});

function selAllRes(box) {
    var chk = $("input[name='cbResID']");
    if (chk != null) {
        chk.attr("checked",box.checked);
    }
}
function loadRes(taskId) {
    if (taskId=="" || taskId<0) {
        taskId = Ext.getCmp("sTaskID").getValue();
    }
    var tblHeader = '<table width="100%" bgColor="#FFFFFF" border="1" class="table1">'+
        '<thead><tr>'+
        '<th title="选择删除"><input type="checkbox" name="chkResID" onclick="selAllRes(this);"/>全选择/全不选</th>'+
        '<th title="任务资源登录名">资源登录名</th>'+
        '<th title="任务资源名称">资源名称</th>'+
        '<th title="资源使用单位">使用单位</th>'+
        '<th title="备注">备注</th>'+
        '</tr></thead>';

    Ext.Ajax.request({
        url : './taskAjax.php',
        params : {strAction:'resourceList',strTaskID:taskId },
        success: function(response,options ) {
            //Ext.Msg.alert('info', response.responseText);
            var rtnData = Ext.decode(response.responseText);
            var tblBody = "";
            if (rtnData.total > 0) {
                var rd;
                for (var i=0; i<rtnData.data.length; i++) {
                    rd=rtnData.data[i];
                    tblBody += '<tr '+(i % 2 === 0 ? "" : "class=t1")+'>'+
                    '<td><input type="checkbox" name="cbResID" value="'+rd.strID+'"/>'+
                    '<a href="javascript:editResourse('+rd.strID+');"> 修改</a></td>'+
                    '<td>'+(rd.strUserName=='task_res_other'?"无":rd.strUserName)+'</td>'+
                    '<td>'+rd.strTrueName+'</td>'+
                    '<td align="center">'+rd.strUsageUnit+'%</td>'+
                    '<td>'+rd.strRemark+'</td>'+
                    '</tr>';
                }
            }
            if (xgResource && xgResource.body) {
                xgResource.body.update(tblHeader+tblBody+'</table>');
            }
        },
        failure: function(response,options ) {
            Ext.Msg.alert('error',response.responseText);
        }
    });
}
function editResourse(resId) {
    Ext.Ajax.request({
        url : './taskAjax.php',
        params : {strAction:'resourceList',strID:resId },
        success: function(response,options ) {
            //Ext.Msg.alert('info', response.responseText);
            var rtnData = Ext.decode(response.responseText);
            if (rtnData.total >= 1) {
                var rd = rtnData.data[0];
                winRes.show();
                frmRes.form.reset();
                fn_sDd("btnResDel",false);
                Ext.getCmp("idResID").setValue(rd.strID);
                Ext.getCmp("idResRemark").setValue(rd.strRemark);
                Ext.getCmp("idResName").setValue(rd.strUserName);
                Ext.getCmp("idResName").selectByValue(rd.strUserName,true);
                Ext.getCmp('idTruename').setValue(rd.strTrueName);
                Ext.getCmp("idUsePercent").setValue(rd.strUsageUnit);
                Ext.getCmp("idUsePercent").selectByValue(rd.strUsageUnit,true);
            }
        },
        failure: function(response,options ) {
            Ext.Msg.alert('error',response.responseText);
        }
    });
}

var xgResource = new Ext.Panel({
    frame :true,
    region:'center',
    layout:'form',
    title :'完成该任务的资源安排',
    tbar:[{
        id:'btnAdd2',
        disabled:true,
        text:'新增',
        tooltip:'新增资源',
        iconCls:'btn_add',
        handler:function() {
            winRes.show();
            frmRes.form.reset();
            Ext.getCmp("idUsePercent").setValue("100");
            fn_sDd("btnResDel",true);}
    }, '-', {
        id:'btnDel2',
        disabled:true,
        text:'批量删除',
        tooltip:'批量删除已经选择的资源',
        iconCls:'btn_remove',
        handler:function() {
            var records = $("input[name='cbResID']:checked"); //得到被选择的行的数组
            var resIDs = "";
            records.each(function() {
                if (resIDs.length > 0) {
                    preIDs += "," + this.value;
                } else {
                    resIDs += this.value;
                }
            });
            if (resIDs.length == 0){ 
                Ext.Msg.alert("系统提示信息","请先选择一行或多行进行删除！");
            } else {
                Ext.Ajax.request({
                    url: './taskAjax.php',
                    params : {strAction:'batchDelRes',strResIDS:resIDs },
                    success: function() {loadRes("");},
                    failure: function(form,action) {Ext.Msg.alert('批量删除数据',action.result.msg);}
                });
            }
        }
    }, '-', {
        text:'刷新',
        tooltip:'重新加载数据',
        iconCls:'btn_refresh',
        handler:function() {loadRes("");}
    }]
});

function changeResMan(comb,record,index) {
    Ext.getCmp('idTruename').setValue(record.get("sValue")=='task_res_other'?"":record.get("sText"));
}
//维护资源信息
var frmRes = new Ext.FormPanel({
    baseCls: 'x-plain',
    labelWidth: 70,
    labelAlign: 'left',
    buttonAlign:'center',
    bodyStyle : 'padding-top:5px',
    defaultWidth:'175',
    items: [{
        xtype:"combo",id:"idResName",fieldLabel:"资源名称",displayField:'sText',valueField:'sValue',
        allowBlank:false, blankText:'资源名称不能为空',mode:'remote',anchor:'92%',
        hiddenName:"strResName",listeners:{'select':changeResMan},
        store:new Ext.data.JsonStore({url:'taskAjax.php?strAction=resNameList',root:'data',
            fields:['sValue','sText'],autoLoad:true })
    },{
        xtype:"textfield",fieldLabel:'手工填写',id:'idTruename',name:"strTruename",vtype:'dblCharField',anchor:'92%',
        allowBlank:false,blankText:'真实姓名不能为空',maxLength:50
    },{
        xtype:"combo",id :"idUsePercent",fieldLabel:"使用单位",valueField:'sValue',
        allowBlank:false, blankText:'使用单位不能为空',anchor:'92%',hiddenName:"strUsePercent",
        store:new Ext.data.SimpleStore({
            data: [ <{ section name="loop_user" loop=101 max=19 step=-5 }>
                    ["<{ $smarty.section.loop_user.index }>","<{ $smarty.section.loop_user.index }>%"],
                    <{ /section }> ['5','5%']],
            fields:['sValue','sText']
        })
    },{xtype:"textfield",fieldLabel:'备注',id:'idResRemark',name:"strResRemark",vtype:'dblCharField',anchor:'92%',maxLength:120},
    {xtype:"hidden",name:"strResID",id:'idResID',value:''}],

    buttons: [{
        text:'保存',
        handler:function(){
            if  (frmRes.form.isValid()) {
                frmRes.form.submit({
                    url : './taskAjax.php',  method  : 'POST',
                    params  : {strAction:(Ext.getCmp("idResID").getValue()==""?'addRes':'updateRes'),
                                       strTaskID:Ext.getCmp("sTaskID").getValue()},
                    success : function(form, action){
                        //Ext.Msg.alert('提示', action.result.msg);
                        loadRes(""); winRes.hide();
                        },
                    failure : function(form, action) {
                            Ext.Msg.alert('数据保存失败！',action.result.msg);
                    }
                });
            } else {
                Ext.Msg.show({title:'错误', msg:"数据错误，请检查", buttons: Ext.Msg.OK, icon: Ext.Msg.ERROR});
            }
        }
    },{
        text:'删除',id:'btnResDel',
        handler:function(){
            frmRes.form.submit({
                url     : './taskAjax.php',
                method  : 'POST',
                params  : {strAction:'deleteRes'},
                success : function(form,action) {
                    loadRes(""); winRes.hide();
                },
                failure : function(form,action) {
                    Ext.Msg.alert('数据删除失败！',action.result.msg);
                }
            });
        }
    },{
        text:'取消',handler:function(){winRes.hide();}
     }]
});
var winRes = new Ext.Window({
    title: '资源维护',
    width: 360,height:200,collapsible:true, maximizable:false,
    layout:'fit',plain:true,bodyStyle:'padding:5px;',
    modal:true,closeAction:'hide',items:frmRes
});

var taskInfo = new Ext.TabPanel({
    region    : 'center',
    resizeTabs: false,
    border    : false,
    tabWidth  : 120,
    activeTab : 0,
    defaults  : {autoScroll : true,autoShow :true},
    items     : [{
        title    : '基本信息',
        id       : 'tabBase',
        layout   : 'fit',
        items    : taskForm
     },{
        title    : '前置任务',
        id       : 'tabPreTask',
        layout   : 'fit',
        items    : xgPreTask
     },{ 
        title    : '资源选择',
        id       : 'tabRes',
        layout   : 'fit',
        items    : xgResource
    }]
});

var viewport = new Ext.Viewport({
    layout:'border',
    items : [taskTree,taskInfo]
});

//must active each other
taskInfo.activate('tabRes');
taskInfo.activate('tabPreTask');
taskInfo.activate('tabBase');

//check on and calculate duration
Ext.getCmp("isAutoCalc").on("check",function(chk,checked){if (checked) calcDuration();});
//-->
</script>

<br/>
</body>
</html>